package xyz.chatboxapp.chatbox.ai;

import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OpenAiService {
    private static final String TAG = "SystemOverlay";
    private OkHttpClient httpClient;
    
    public OpenAiService() {
        httpClient = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
    }
    
    public interface Callback {
        void onSuccess(String candidatesJson);
        void onError(String errorCode, String errorMessage);
    }
    
    public void generateCandidates(String baseUrl, String model, double temperature, double topP, String userText, String apiKey, Callback callback) {
        try {
            // Build OpenAI-compatible API URL
            String apiUrl;
            if (baseUrl.endsWith("/v1") || baseUrl.endsWith("/v1/")) {
                apiUrl = baseUrl.replaceAll("/$", "") + "/chat/completions";
            } else if (baseUrl.endsWith("/")) {
                apiUrl = baseUrl + "v1/chat/completions";
            } else {
                apiUrl = baseUrl + "/v1/chat/completions";
            }
            
            Log.i(TAG, "OPENAI request url=" + apiUrl);
            
            // Build OpenAI-compatible chat completion request using the passed-in final prompt
            JSONObject body = new JSONObject();
            body.put("model", model);
            body.put("temperature", temperature);
            body.put("top_p", topP);
            JSONArray messages = new JSONArray();
            messages.put(new JSONObject().put("role", "user").put("content", userText));
            body.put("messages", messages);
            
            // Debug: prompt preview
            try {
                String prev = userText.replaceAll("\\s+", " ");
                if (prev.length() > 200) prev = prev.substring(0, 200);
                Log.i(TAG, "OPENAI prompt preview len=" + userText.length() + " preview=\"" + prev + "\"");
            } catch (Exception ignored) {}
            
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            final Request req = new Request.Builder()
                    .url(apiUrl)
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .addHeader("Content-Type", "application/json")
                    .post(RequestBody.create(body.toString(), JSON))
                    .build();
            
            new Thread(() -> {
                try (Response resp = httpClient.newCall(req).execute()) {
                    Log.i(TAG, "OPENAI http status=" + resp.code());
                    
                    if (!resp.isSuccessful()) {
                        String emsg = "HTTP " + resp.code();
                        try {
                            String bodyS = resp.body() != null ? resp.body().string() : "";
                            Log.w(TAG, "OPENAI http_error bodyLen=" + (bodyS != null ? bodyS.length() : 0));
                        } catch (Exception ignored) {}
                        callback.onError("http_error", emsg);
                        return;
                    }
                    
                    String respStr = resp.body() != null ? resp.body().string() : "";
                    Log.i(TAG, "OPENAI resp len=" + (respStr != null ? respStr.length() : 0));
                    
                    JSONObject rj = new JSONObject(respStr);
                    JSONArray choices = rj.optJSONArray("choices");
                    if (choices == null || choices.length() == 0) {
                        callback.onError("no_choices", "No choices returned");
                        return;
                    }
                    
                    JSONObject first = choices.getJSONObject(0);
                    JSONObject message = first.optJSONObject("message");
                    String content = message != null ? message.optString("content", "") : first.optString("text", "");
                    if (content == null) content = "";
                    
                    // Debug: content preview
                    try {
                        String prev = content.replaceAll("\\s+", " ");
                        if (prev.length() > 200) prev = prev.substring(0, 200);
                        Log.i(TAG, "OPENAI content preview len=" + content.length() + " preview=\"" + prev + "\"");
                    } catch (Exception ignored) {}
                    
                    JSONObject payload;
                    try { 
                        payload = new JSONObject(content); 
                    } catch (Exception pe) {
                        payload = new JSONObject();
                        JSONArray arr = new JSONArray();
                        if (content.length() > 0) arr.put(content);
                        payload.put("candidates", arr);
                    }
                    
                    callback.onSuccess(payload.toString());
                } catch (Exception e) {
                    String msg = e.getMessage() == null ? "error" : e.getMessage().replace("\n", " ");
                    Log.e(TAG, "OPENAI exception: " + msg);
                    callback.onError("exception", msg);
                }
            }).start();
        } catch (Exception e) {
            String msg = e.getMessage() == null ? "error" : e.getMessage().replace("\n", " ");
            Log.e(TAG, "generateCandidates() bad_args: " + msg);
            callback.onError("bad_args", msg);
        }
    }
}